#!/usr/bin/env python3
# -*- encoding: utf-8 -*-
'''
@author: yuejl
@application:
@contact: lewyuejian@163.com
@file: httpclient.py
@time: 2021/10/17 0017 21:49
@desc:
'''
import re
import copy
import allure
import requests
from typing import List
from urllib.error import URLError
from integratior_service.controllers.common.parser import build_url
from integratior_service.controllers.config.regex_match_rules import _URL_REGEX
from integratior_service.controllers.common.models import RequestData as request_obj
#from integratior_service.connector.base_obj.connector_obj import ConnectorObj as connector_obj

class HttpClient(requests.Session):

    def __init__(self, test_case_list, global_vars=None):
        super(HttpClient, self).__init__()
        if not isinstance(test_case_list, List):
            raise ValueError('test_case_list must be a list!')

        self._test_case_list = test_case_list
        self._session = requests.Session()
        self._url = ''

        self._origin_global_vars = global_vars if global_vars else {}
        self.global_vars = copy.deepcopy(self._origin_global_vars)

    default_headers = request_obj.headers.setdefault("Content-Type", "application/json")

    def setHeaders(self, headers):
        request_obj.headers = headers

    def updateHeaders(self, headers):
        if headers:
            request_obj.headers.update(headers)

    def getHeaders(self):
        return request_obj.headers

    def setCookies(self, cookies):
        request_obj.cookies = cookies

    def updateCookies(self, cookies):
        request_obj.cookies.update(cookies)

    def getCookies(self):
        return request_obj.cookies

    def setTimeout(self,seconds):
        self._timeout=seconds

    def _send_request_mode(self, url, method, **kwargs):
        url_match = _URL_REGEX.match(url)
        if url_match is None:
            raise URLError(f"Unvalid url >>> {url}")
        resp = self._session.request(method, url, **kwargs)
        return resp

    def send_requestV2(self, variables, isJson=True):
        if variables.get('url'):
            request_obj.url = build_url(self._url, variables.get('url'))
        else:
            request_obj.url = self._url

        _cache = ''

        body_data = ''

        request_obj.method = variables.get('method')

        if request_obj.method in ['post', 'POST', '']:
            if isJson:
                resp = self._send_request_mode(request_obj.url, 'post', json=body_data, headers=request_obj.headers)
            else:
                resp = self._send_request_mode(request_obj.url, 'post', data=body_data, headers=request_obj.headers)
        elif request_obj.method in ['get', 'GET']:
            resp = self._send_request_mode(request_obj.url, 'get', params=body_data)
        self.create_response_log(resp.status_code, resp.text)
        return resp

    @allure.step("请求日志")
    def create_request_log(self, url, method, body, header):
        pass

    @allure.step('响应日志')
    def create_response_log(self, status_code, text):
        pass



